<template>
  <el-tree-select
    v-model="selectValue"
    :data="options"
    :props="defaultProps"
    value-key="id"
    placeholder="请选择上级分类"
    clearable
    class="w-full"
    @change="handleChange"
  />
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { listCategory } from '@/api/cms/category';
import type { CategoryNode } from '@/api/cms/category/types';

const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: 0
  },
  categoryType: {
    type: String,
    required: true
  }
});

const emit = defineEmits(['update:modelValue', 'change']);

const selectValue = ref(props.modelValue);
const options = ref<CategoryNode[]>([]);

const defaultProps = {
  value: 'id',
  label: 'categoryName',
  children: 'children'
};

// 加载分类树数据
const loadData = async () => {
  try {
    const res = await listCategory({ 
      categoryType: props.categoryType,
      status: '0' 
    });
    options.value = [{
      id: 0,
      categoryName: '顶级分类',
      children: res.data
    }];
  } catch (error) {
    console.error('获取分类列表失败:', error);
  }
};

// 监听值变化
watch(() => props.modelValue, (val) => {
  selectValue.value = val;
});

watch(() => props.categoryType, () => {
  loadData();
});

// 处理选择变化
const handleChange = (value: number) => {
  emit('update:modelValue', value);
  emit('change', value);
};

// 初始化
loadData();
</script> 